/*
 * @Author: luojianfeng
 * @Date: 2025-10-15 16:34:51
 * @LastEditTime: 2025-10-15 16:34:57
 * @LastEditors: luojianfeng
 * @Description:
 */
/**
 * 返回有效代码区间数组（跳过 //  /* ... * /）
 * 每个区间: { start: number, end: number }
 */
export function getCodeRanges(code: string): { start: number; end: number }[] {
  const ranges: { start: number; end: number }[] = []
  let inMulti = false
  let lastEnd = 0

  const lines = code.split('\n')
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]
    const lineStart =
      code.split('\n').slice(0, i).join('\n').length + (i > 0 ? 1 : 0)
    const lineEnd = lineStart + line.length

    /* 多行注释开始 / * */
    const multiStart = line.indexOf('/*')
    if (multiStart !== -1 && !inMulti) {
      ranges.push({ start: lastEnd, end: lineStart + multiStart })
      inMulti = true
    }
    /* 多行注释结束 * / */
    const multiEnd = line.indexOf('*/')
    if (multiEnd !== -1 && inMulti) {
      lastEnd = lineStart + multiEnd + 2
      inMulti = false
      continue
    }
    if (inMulti) continue

    /* 单行注释 // */
    const single = line.indexOf('//')
    if (single !== -1) {
      ranges.push({ start: lastEnd, end: lineStart + single })
      lastEnd = lineEnd
      continue
    }

    /* 整行都是代码 */
    ranges.push({ start: lastEnd, end: lineEnd })
    lastEnd = lineEnd + 1 // 换行符
  }

  /* 文件尾部 */
  if (lastEnd < code.length) ranges.push({ start: lastEnd, end: code.length })
  return ranges
}
